<template>
  <div class="student-courses-progress">
    <!-- 顶部标题和统计信息 -->
    <el-page-header title="返回" @back="goBack">
      <template #content>
        <h1>{{ studentName }}的学习进度总览</h1>
      </template>
    </el-page-header>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="5" animated />
    </div>

    <!-- 错误状态 -->
    <div v-else-if="error" class="error-container">
      <el-alert :title="error" type="error" show-icon />
      <el-button type="primary" @click="retryInitData">重试</el-button>
    </div>

    <!-- 内容区域 -->
    <template v-else>
      <!-- 总体进度卡片 -->
      <el-card class="overall-progress-card">
        <div class="progress-header">
          <h2>总体学习进度</h2>
          <el-tag :type="getProgressTagType(overallProgress)" size="large">
            {{ (overallProgress * 100).toFixed(1) }}%
          </el-tag>
        </div>
        <el-progress 
          :percentage="overallProgress * 100" 
          :stroke-width="16"
          :color="getProgressColor(overallProgress)"
          :show-text="false"
        />
        <div class="stats">
          <div class="stat-item">
            <span class="stat-label">已学课程</span>
            <span class="stat-value">{{ completedCoursesCount }} / {{ courses.length }}</span>
          </div>
          <div class="stat-item">
            <span class="stat-label">平均进度</span>
            <span class="stat-value">{{ (overallProgress * 100).toFixed(1) }}%</span>
          </div>
        </div>
      </el-card>

      <!-- 课程列表 - 确保每个课程都有展示 -->
      <div class="course-list">
        <el-card 
          v-for="course in courses" 
          :key="course.courseId" 
          class="course-card"
          shadow="hover"
        >
          <div class="course-header">
            <h3>{{ course.courseName || '未命名课程' }}</h3>
            <el-tag :type="getProgressTagType(course.overallProgress)" size="medium">
              {{ ((course.overallProgress || 0) * 100).toFixed(1) }}%
            </el-tag>
          </div>
          
          <!-- 课程总体进度条 -->
          <el-progress 
            :percentage="(course.overallProgress || 0) * 100" 
            :stroke-width="10"
            :color="getProgressColor(course.overallProgress)"
          />
          
          <!-- 章节进度详情 - 每个课程都会显示章节区域 -->
          <div class="chapter-section">
            <el-collapse v-model="activeCollapse" accordion>
              <el-collapse-item 
                :title="`章节详情 (${(course.chapterProgressList || []).length})`" 
                :name="course.courseId"
              >
                <template v-if="course.chapterProgressList && course.chapterProgressList.length > 0">
                  <div class="chapter-item" v-for="chapter in course.chapterProgressList" :key="chapter.chapterId">
                    <div class="chapter-info">
                      <span class="chapter-title">{{ chapter.chapterTitle || '未命名章节' }}</span>
                      <span class="chapter-progress">
                        {{ chapter.learnedStatus ? '已完成' : `${Math.floor((chapter.progress || 0) * 100)}%` }}
                      </span>
                    </div>
                    <el-progress 
                      :percentage="(chapter.progress || 0) * 100" 
                      :stroke-width="6"
                      :color="chapter.learnedStatus ? '#67C23A' : '#409EFF'"
                    />
                  </div>
                </template>
                <template v-else>
                  <div class="no-chapters">暂无章节数据</div>
                </template>
              </el-collapse-item>
            </el-collapse>
          </div>
        </el-card>
      </div>
    </template>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElButton } from 'element-plus'
import axios from '@/utils/request'
import { studentApi } from '@/api/students'
import { useAuthStore } from '@/stores/auth'

const route = useRoute()
const router = useRouter()
const authStore = useAuthStore()

// 学生信息
const studentId = ref('')
const studentName = ref('当前学生')
const overallProgress = ref(0)
const courses = ref([])
const activeCollapse = ref('')
const loading = ref(true)
const error = ref(null)

// 计算已完成的课程数量
const completedCoursesCount = computed(() => {
  return courses.value.filter(course => (course.overallProgress || 0) >= 0.95).length
})

// 获取进度颜色
const getProgressColor = (progress) => {
  progress = progress || 0
  if (progress >= 0.9) return '#67C23A' // 绿色
  if (progress >= 0.6) return '#409EFF' // 蓝色
  if (progress >= 0.3) return '#E6A23C' // 黄色
  return '#F56C6C' // 红色
}

// 获取进度标签类型
const getProgressTagType = (progress) => {
  progress = progress || 0
  if (progress >= 0.9) return 'success'
  if (progress >= 0.6) return 'primary'
  if (progress >= 0.3) return 'warning'
  return 'danger'
}

// 获取学生所有课程进度 - 完全适配您的API格式
const fetchAllCoursesProgress = async () => {
  try {
    loading.value = true
    const response = await axios.get('/api/learning-progress/all-courses', {
      params: { studentId: studentId.value }
    })
    
    console.log('API完整响应:', response) // 调试用
    
    // 最简化的验证 - 只要response存在就接受
    if (!response) {
      console.error('API请求失败:', response)
      throw new Error('API请求失败')
    }
    
    // 直接使用响应数据，不进行任何格式验证
    const responseData = response.data || {}
    
    // 处理课程数据 - 完全按照您的API格式
    overallProgress.value = responseData.overallProgress || 0
    courses.value = responseData.coursesProgress || [] // 直接使用原始数据
    
    // 学生姓名也是可选的
    studentName.value = responseData.studentName || studentName.value
    
    // 默认展开第一个课程
    if (courses.value.length > 0) {
      activeCollapse.value = courses.value[0].courseId
    }
    
  } catch (err) {
    console.error('获取课程进度失败:', err)
    error.value = '获取学习进度失败: ' + (err.response?.data?.message || err.message)
    ElMessage.error(error.value)
  } finally {
    loading.value = false
  }
}

// 获取学生ID
const fetchStudentId = async () => {
  try {
    if (!authStore.userId) {
      throw new Error('用户未登录，请先登录')
    }
    
    const response = await studentApi.getStudentIdByUserId(authStore.userId)
    
    // 适配API响应格式 {success: true, data: 35}
    if (!response || !response.success || response.data === undefined) {
      console.error('API响应格式不匹配:', response)
      throw new Error('获取学生ID失败: API响应格式不匹配')
    }
    
    studentId.value = response.data
    studentName.value = '当前学生'
    return true
    
  } catch (err) {
    console.error('获取学生ID失败:', err)
    error.value = '获取学生信息失败: ' + (err.response?.data?.message || err.message)
    ElMessage.error(error.value)
    return false
  }
}

// 初始化加载数据
const initData = async () => {
  try {
    loading.value = true
    error.value = null
    
    // 先获取学生ID
    const success = await fetchStudentId()
    if (success) {
      // 再获取课程进度
      await fetchAllCoursesProgress()
    }
  } catch (err) {
    console.error('初始化数据失败:', err)
    error.value = '初始化数据失败: ' + err.message
  } finally {
    loading.value = false
  }
}

// 重试初始化
const retryInitData = () => {
  initData()
}

// 返回上一页
const goBack = () => {
  router.go(-1)
}

// 初始化加载数据
onMounted(() => {
  initData()
})
</script>

<style scoped>
.student-courses-progress {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.loading-container,
.error-container {
  padding: 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 20px;
}

.overall-progress-card {
  margin-bottom: 24px;
}

.progress-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.progress-header h2 {
  margin: 0;
  font-size: 18px;
}

.stats {
  display: flex;
  margin-top: 16px;
  gap: 24px;
}

.stat-item {
  display: flex;
  flex-direction: column;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.stat-value {
  font-size: 18px;
  font-weight: bold;
  color: #303133;
}

.course-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(500px, 1fr));
  gap: 20px;
}

.course-card {
  margin-bottom: 20px;
}

.course-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.course-header h3 {
  margin: 0;
  font-size: 16px;
}

.chapter-section {
  margin-top: 15px;
}

.chapter-item {
  margin-bottom: 12px;
}

.chapter-info {
  display: flex;
  justify-content: space-between;
  margin-bottom: 6px;
}

.chapter-title {
  font-size: 14px;
  color: #606266;
}

.chapter-progress {
  font-size: 13px;
  color: #909399;
}

.no-chapters {
  text-align: center;
  color: #909399;
  padding: 10px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .course-list {
    grid-template-columns: 1fr;
  }
  
  .student-courses-progress {
    padding: 10px;
  }
}
</style>